import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class demo1 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号 ：");
        int id = scanner.nextInt();
        System.out.println("请输入姓名 ：");
        String name = scanner.next();

        //1.创建datasource
        DataSource dataSource = new MysqlDataSource();
        //向上转型

        ((MysqlDataSource) dataSource).setUrl();
        // 向下转型

        ((MysqlDataSource) dataSource).setUrl("root");
        ((MysqlDataSource) dataSource).setPassword("kkkk");

        //2.建立和数据库服务器之间的连接
        Connection connection = dataSource.getConnection();

        //3.构造sql
        String sql = "insert into student values(?, ?)";
        //String sql = "delete from student where id = 1";
        //String sql = "update student set name = '张三' where id = 100";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2, name);

        //打印sql看效果
        System.out.println("sql = "+ statement);

        //4.把sql发给服务器
        int n = statement.executeUpdate();
        System.out.println("n = " + n);

        //5.释放资源，关闭连接
         statement.close();
         connection.close();
    }

}
